package com.lry.rpc.starter.context;

import com.lry.rpc.starter.config.AbstractConfig;
import com.lry.rpc.starter.util.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;

public class DefaultConfigurationBeanCustomizer implements RpcConfigBeanCustomizer {

    @Override
    public void customize(String beanName, AbstractConfig configBean) {
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(configBean.getClass(), "name");
        if (propertyDescriptor != null) {
            Method getNameMethod = propertyDescriptor.getReadMethod();
            if (getNameMethod == null) {
                return;
            }

            Object propertyValue = ReflectionUtils.invokeMethod(getNameMethod, configBean);
            if (propertyValue != null) {
                return;
            }

            //没有设置name直接拿beanName作为name
            Method setNameMethod = propertyDescriptor.getWriteMethod();
            if (setNameMethod != null && Arrays.equals(ObjectUtils.of(new Class[]{String.class}), setNameMethod.getParameterTypes())) {
                ReflectionUtils.invokeMethod(setNameMethod, configBean, new Object[]{beanName});
            }
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
